<template>
	<cu-custom bgColor="" :isBack="true">
		<template #title>专项督导表单</template>
	</cu-custom>
	
	<view class="form">
		<view class="header">
			{{ formDetail.name }}
		</view>
		<view class="des">
			{{ formDetail.description }}
		</view>
		<view class="info">
			<view>创建时间：{{ formDetail.createtime }}</view>
			<view v-if="userInfo.role === 1">当前状态：
				<text :class="formDetail.status !== '0' ? 'text-green' : 'text-orange'">
					{{ formDetail.status !== '0' ? "已完成": "未完成" }}
				</text>
			</view>
		</view>
		<view class="default-box mb-3" v-for="(field, index) in dataList">
			<view class="middle-text text-bold">{{ index + 1 }}、{{ field.fieldIssue }}</view>
			<view class="hint text-gray small-text" style="margin-left: 60rpx;" v-if="field.fieldTips">
				{{ "注：" + field.fieldTips }}
			</view>
			<view class="mb-3"></view>
				
			<view class="field-box">
				<!-- 单选框 -->
				<view class="mb-3" v-if="field.fieldType === 'radio'">
					<radio-group @change="(e: any) => radioChange(e, field)">
						<label class="uni-list-cell" v-for="(option, optionIndex) in field.fieldOptions" :key="optionIndex">
							<view class="uni-list-cell-radio">
								<radio
									:value="option.label"
									:checked="option.checked"
									:disabled="formDetail.status === '1'"
									:class="{
										'disabled': formDetail.status === '1' && option.checked
									}"
								/>
							</view>
							<view class="">{{ option.label }}</view>
						</label>
					</radio-group>
				</view>
				
				<!-- 多选框 -->
				<view class="mb-3" v-if="field.fieldType === 'checkbox'">
					<checkbox-group @change="(e: any) => checkboxChange(e, field)">
						<label class="uni-list-cell" v-for="(option, optionIndex) in field.fieldOptions" :key="optionIndex">
							<view class="uni-list-cell-radio">
								<checkbox
									:value="option.label"
									:checked="option.checked"
									:disabled="formDetail.status === '1'"
								/>
							</view>
							<view class="">{{ option.label }}</view>
						</label>
					</checkbox-group>
				</view>
				
				<!-- 输入框 -->
				<view class="mb-3" v-if="field.fieldType === 'input'">
					<input
						style="border-bottom: 2rpx solid #bf7b04;"
						type="text"
						:placeholder="calPlaceholderText(field)"
						:maxlength="field.valueCountMax"
						v-model="field.fieldValue"
						:disabled="formDetail.status === '1'"
					/>
				</view>
				
				<!-- 多行输入框 -->
				<view class="mb-3" v-if="field.fieldType === 'textarea'">
					<textarea
						style="border: 2rpx solid #eee; border-radius: 6rpx; padding: 4rpx 10rpx"
						type="text"
						:placeholder="calPlaceholderText(field)"
						v-model="field.fieldValue"
						:maxlength="field.valueCountMax"
						:disabled="formDetail.status === '1'"
					>
					</textarea>
				</view>
				
				<!-- 多项填空题 20240308 取消这种类型的填空题 -->
				<view class="mb-3" v-if="field.fieldType === 'multInput'">
					<view class="mb-3" v-for="(input, mult_index) in field.fieldValue" :key="mult_index">
						<input
							style="border-bottom: 2rpx solid #bf7b04;"
							type="text"
							placeholder="请输入文字"
							maxlength="200"
							:value="input"
							@input="(e: any) => multInputChange(e, field, mult_index)"
							:disabled="formDetail.status === '1'"
						/>
					</view>
					<view class="add-btn" @click="addMultInput(field)">新增</view>
				</view>
				
				
				<!-- 打分 -->
				<view class="mb-3" v-if="field.fieldType === 'score'">
					<input
						style="border-bottom: 2rpx solid #bf7b04;"
						type="number"
						:placeholder="calPlaceholderText(field)"
						v-model="field.fieldValue"
						max="10"
						:disabled="formDetail.status === '1'"
					/>
					<!-- <Score
						v-model:score="field.fieldValue"
						:disabled="formDetail.status === '1'"
					></Score> -->
				</view>
				
				<view class="remark mb-3">
					<input
						type="text"
						placeholder="备注"
						v-model="field.remark"
						:disabled="formDetail.status === '1'"
						@input="fieldChange(field)"
					/>
				</view>
				
				<view class="upload">
					<view class="text-black mb-1">附件：</view>
					<Upload
						v-model:field-files="field.fieldFiles"
						:disabled="formDetail.status === '1'"
						@change="fieldChange(field)"
					></Upload>
				</view>
			</view>
			
			
			<!-- <checkbox-group class="block" @change="checkboxChange">
				<view class="cu-form-group" v-for="(item, index) in checkboxData" :key="index">
					<view class="title text-ellipsis-1">{{ item.name }}</view>
					<checkbox
						class="round"
						activeBackgroundColor="#3974df"
						:checked="item.checked ? true : false"
						:value="item.value">
					</checkbox>
				</view>
			</checkbox-group> -->
			
			
		</view>
		
		<view class="bottom-btn theme-shadow" v-if="formDetail.status === '0'">
			<CuButton size="small" :disabled="submitDisable" @click="handleSave">提交</CuButton>
		</view>
		<!-- <view class="mb-4" v-if="formDetail.status === '0'">
			<CuButton size="small" :disabled="submitDisable" @click="handleSubmit">提交</CuButton>
		</view> -->
	</view>
	
		
</template>
<script setup lang="ts">
import { Ref, ref, reactive } from "vue"
import { getForm, updateForm, submitForm } from "@/api/mission.js"
import { onLoad } from "@dcloudio/uni-app"
import CuButton from "@/components/CuButton.vue"
import { router } from "@/router"
import Score from "@/components/Score.vue"
import Upload from "@/components/Upload.vue"
import store from "@/store/index.js"

interface IOption {
	label: string
	checked: boolean
}
interface IFile {
	fileName: string
	fileUrl: string
}
interface IField {
	id: number
	fieldIssue: string
	fieldType: string
	fieldOptions?: any[]
	valueType: string
	statistics: boolean
	required: boolean
	valueCountMin?: number
	valueCountMax?: number
	sort?: number
	checkIndex?: number
	multInputTotalCount?: number | string
	valueScopeMin?: number
	valueScopeMax?: number
	remark: string
	value: any,
	fieldValue: any,
	uploadFiles: IFile[]
	fieldFiles: any[]
	fieldTips: string
}
const props = defineProps({
	mission_id: {
		type: String,
		default: ""
	},
	form_id: {
		type: String,
		default: ""
	}
})

const submitDisable:Ref<boolean> = ref(false)
const multInputChange = (e: any, field: IField, inputIndex: number) => {
	field.fieldValue[inputIndex] = e.detail.value
}
const userInfo = reactive(store.getters.userInfo)

const formDetail = reactive({
	name: "",
	description: "",
	createtime: "",
	status: ""
})
const dataList: Ref<IField[]> = ref([] as IField[])

const calPlaceholderText = (field: IField) => {
	if (field.fieldType === "input" || field.fieldType === "textarea") {
		if (field.valueCountMax) {
			return "请输入文字，不超过" + field.valueCountMax + "字"
		}
	}
	if (field.fieldType === "score") {
		return "最高" + (field.valueScopeMax || 100) + ""
	}
}

//单选框改变
const radioChange = (e: any, field: IField) => {
	field.fieldValue = [e.detail.value]
	fieldChange(field)
}

// 复选框改变
const checkboxChange = (e: any, field: IField) => {
	field.fieldValue = e.detail.value
	fieldChange(field)
}

// 任意一项发生改变
const fieldChange = (field: IField) => {
	// console.log("fieldChange", field)
	const data_key = `cache_form_${props.mission_id}_${props.form_id}`
	const cache_data = uni.getStorageSync(data_key) || { data: {} }
	cache_data.data[field.id] = {
		remark: field.remark,
		uploadFiles: Array.from(field.fieldFiles, (file: any) => ({
			fileName: file.filename,
			fileUrl: file.serverPath
		})),
		value: typeof field.fieldValue === "object" ? JSON.stringify(field.fieldValue) : field.fieldValue
	}
	uni.setStorageSync(data_key, cache_data)
}


const addMultInput = (field: IField) => {
	if (field.fieldValue.length < field.multInputTotalCount) {
		field.fieldValue.push("")
	} else {
		uni.showToast({
			icon: "none",
			title: "最多输入" + field.multInputTotalCount + "个"
		})
	}
}

const fieldValueCheck = (options: IOption[], checkArr: string[]) => {
	const arr = []
	options.map(option => {
		let ischecked = false
		// console.log("checkArr", checkArr)
		for (let v of checkArr) {
			if (option.label === v) {
				ischecked = true
				break
			}
		}
		arr.push({
			label: option.label,
			checked: ischecked
		})
	})
	return arr
}

const loadData = (form_id: any, mission_id: string) => {
	getForm({ formId: form_id, taskId: mission_id })
		.then((res) => {
			console.log(res)
			formDetail.name = res.form.name
			formDetail.description = res.form.description
			formDetail.createtime = res.form.createTime.substring(0, 10)
			formDetail.status = res.wor ? res.wor.status : "0"
			
			if (store.getters.userInfo.role === 2) {
				// 如果是学校联络人 那么表单状态固定为已完成无法修改
				formDetail.status = "1"
			}
			
			// 初始化数据 选择项、备注和文件的默认值
			res.items.map((item: any) => {
				if (item.fieldType === "radio" || item.fieldType === "checkbox") {
					const options = JSON.parse(item.fieldOptions)
					const fieldOptions: IOption[] = []
					options.map((option: any) => {
						fieldOptions.push({
							label: option,
							checked: false
						})
					})
					item.fieldOptions = fieldOptions
				}
				if (item.fieldType === "multInput") {
					item.fieldValue = [""]
				}
				item.remark = ""
				item.fieldFiles = []
			})
			
			// 加载填写记录 如果本地也有就优先本地的缓存
			const form_cache = uni.getStorageSync(`cache_form_${props.mission_id}_${props.form_id}`) || { data: {} }
			
			res.items.map((item: any) => {
				if ((!item.value && item.value !== 0) && !form_cache.data[item.id]) return
				const cache_data = form_cache.data[item.id] ? form_cache.data[item.id] : item.value
				console.log("cache_data", cache_data)
				item.remark = cache_data.remark
				if (cache_data.uploadFiles) {
					cache_data.uploadFiles.map((file: IFile) => {
						item.fieldFiles.push({
							localPath: "",
							serverPath: file.fileUrl,
							suffix: file.fileName.match(/\.([0-9a-z]+)(?:[\?#]|$)/i)[1],
							filename: file.fileName
						})
					})
				}
				
				if (item.fieldType === "radio" || item.fieldType === "checkbox") {
					const checkArr = cache_data.value ? JSON.parse(cache_data.value) : []
					item.fieldValue = checkArr
					item.fieldOptions = fieldValueCheck(item.fieldOptions, checkArr || [])
				}
				// if (item.fieldType === "multInput") {
				// 	item.fieldValue = cache_data && cache_data.value ? JSON.parse(cache_data.value) : item.fieldValue
				// }
				if (item.fieldType === "input") {
					item.fieldValue = cache_data.value
				}
				if (item.fieldType === "textarea") {
					item.fieldValue = cache_data.value
				}
				if (item.fieldType === "score") {
					item.fieldValue = Number(cache_data.value)
				}
			})
			dataList.value = res.items
			console.log(dataList.value)
		})
}


/**
 * 保存草稿
 */
const handleSave = () => {
	console.log(dataList.value)
	const itemValues = []

	for (let index in dataList.value) {
		const field = dataList.value[index]
		// if (!field.fieldValue && field.remark &&) return
		
		const uploadFiles: IFile[] = []
		if (field.fieldFiles.length > 0) {
			field.fieldFiles.map((file) => {
				uploadFiles.push({
					"fileName": file.filename,
					"fileUrl": file.serverPath
				})
			})
		}
		itemValues.push({
			itemId: field.id,
			value: typeof field.fieldValue === "object" ? JSON.parse(JSON.stringify(field.fieldValue)) : field.fieldValue,
			remark: field.remark,
			uploadFiles
		})
	}
	console.log(itemValues)
	// return 
	submitDisable.value = true
	updateForm({
		formId: props.form_id, 
		taskId: props.mission_id,
		itemValues
	}).then((res) => {
		uni.showToast({
			icon: "none",
			title: "操作成功"
		})
		setTimeout(() => {
			router.back()
		}, 1500)
	})
}

/**
 * 保存并提交
 */
const handleSubmit = () => {
	console.log(dataList.value)
	const itemValues = []

	for (let index in dataList.value) {
		const field = dataList.value[index]
		if (field.fieldType === "score") {
			if (field.fieldValue > field.valueScopeMax || field.fieldValue < field.valueScopeMin) {
				uni.showToast({ title: `题[${Number(index) + 1}] 输入值超出范围`, icon: "none" })
				return
			}
		}
		if (field.required) {
			if (!field.fieldValue && field.fieldValue !== 0) {
				uni.showToast({ title: `题[${Number(index) + 1}] 必填`, icon: "none" })
				return
			}
		}
		const uploadFiles: IFile[] = []
		if (field.fieldFiles.length > 0) {
			field.fieldFiles.map((file) => {
				uploadFiles.push({
					"fileName": file.filename,
					"fileUrl": file.serverPath
				})
			})
		}
		itemValues.push({
			itemId: field.id,
			value: typeof field.fieldValue === "object" ? JSON.parse(JSON.stringify(field.fieldValue)) : field.fieldValue,
			remark: field.remark,
			uploadFiles
		})
	}
	console.log(itemValues) 
	// return 
	
	submitDisable.value = true
	updateForm({
		formId: props.form_id, 
		taskId: props.mission_id,
		itemValues
	}).then(res => {
		submitForm({
			formId: props.form_id,
			taskId: props.mission_id
		}).then((res) => {
			uni.showToast({
				icon: "none",
				title: "提交成功"
			})
			setTimeout(() => {
				router.back()
			}, 1500)
		})
	})
}

onLoad((options) => {
	if (options.form_id) {
		loadData(options.form_id, options.mission_id)
	}
})
</script>

<style lang="stylus" scoped>
.form
	background: #fff
	padding-bottom 22rpx
	.header
		text-align: center
		font-size 38rpx
		font-weight: bold
		padding 40rpx 20rpx
	.des
		font-size 26rpx
		padding 0 40rpx 20rpx
	.info
		display: flex
		justify-content: space-between
		padding 0 40rpx 20rpx
.default-box
	border-bottom: 2rpx solid #eee
	border-radius: 0
	.field-box
		padding 0 40rpx
		.remark
			border-bottom: 2rpx solid #f1f1f1
		.uni-list-cell
			display: flex
			align-items: center
			margin-bottom: 12rpx
			.uni-list-cell-radio
				padding-right: 14rpx
.add-btn
	display: inline
	background #3974df
	color #fff
	padding 10rpx 30rpx
	border-radius: 8rpx
	transition: all .3s 
.add-btn:active	
	background: #2d5db1
.disabled
	>>> .uni-radio-input-disabled
		background-color #3974df!important
.bottom-btn
	position: fixed
	bottom: 0
	width: 100%
	background: #fff
	padding: 20rpx 0
</style>